import { DPGroupModel } from '../model/DPGroupModel';
import { assign, forEach, isNull, trim } from 'lodash-es';
import { UserModel } from '../model/UserModel';
import { DPPgyModel } from '../model/DPPgyModel';

class DPGroupService {
  async getList(page: number, pagesize: number) {
    return await DPGroupModel.findAndCountAll({
      limit: pagesize,
      offset: (page - 1) * pagesize,
    });
  }
  async addTopic(values: any) {
    const user = global.userinfo as UserModel;
    const res = await DPGroupModel.create(
      assign(values, { createId: user.id, creator: user.realName }),
    );
    //处理蒲公英平台数据
    if (res.type == 1) {
      const data = values['pgy_data'];
      forEach(data, (item: DPPgyModel) => {
        item.groupId = res.id;
        item.name = trim(item.name);
      });
      await DPPgyModel.bulkCreate(data);
    }
  }
  //更新导出列
  async updateColumns(values: any) {
    const row = await DPGroupModel.findByPk(values['id']);
    if (isNull(row)) {
      throw new global.errs.ParameterException('记录不存在', 400);
    }
    await DPGroupModel.update({ columns: values['columns'] }, { where: { id: values['id'] } });
  }
  //开始抓取数据
  async startFetch(id: number) {
    const row = await DPGroupModel.findByPk(id);
    if (isNull(row)) {
      throw new global.errs.ParameterException('记录不存在', 400);
    }
    if (row.status == 1 || row.status == 2) {
      throw new global.errs.ParameterException('抓取已开始,无需重复操作', 400);
    }
    await DPGroupModel.update({ status: 1, statusMsg: '数据抓取中……' }, { where: { id: id } });
  }
  //获取任务信息
  async fineOne(id: number) {
    const row = await DPGroupModel.findByPk(id);
    if (isNull(row)) {
      throw new global.errs.ParameterException('记录不存在', 400);
    }
    return row;
  }

  async updateStatus(id: number, gid: number, key: string, value: string) {
    const groupModel = await DPGroupModel.findByPk(gid);
    if (isNull(groupModel)) {
      throw new global.errs.ParameterException('记录不存在', 400);
    }
    if (groupModel.status == 2) {
      throw new global.errs.ParameterException('已完成无需修改', 400);
    }
  }
}

export default new DPGroupService();
